<template>
  <div>
    <common-head :title="$route.name"/>
    <div class="address">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="changeContact"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchAddress } from '_api'
import { getToken } from '_utils'
export default {
  data () {
    return {
      chosenAddressId: '',
      list: []
    }
  },
  created () {
    this.fetchAddress()
  },
  methods: {
    // 获取联系人列表
    fetchAddress () {
      fetchAddress({ token: getToken() }).then(res => {
        if (res.data.code === 0) {
          const arr = res.data.data.result
          // 字段映射 因为框架组件字段和后端返回的字段名不一致
          const list = []
          arr.forEach(item => {
            const obj = {}
            for (const key in item) {
              if (key === 'linkMan') {
                obj.name = item[key]
              } else if (key === 'mobile') {
                obj.tel = item[key]
              } else {
                obj[key] = item[key]
              }
            }
            list.push(obj)
          })
          this.list = list
          // 找到默认联系人的id
          const defaultMan = list.find(item => item.isDefault)
          if (defaultMan) {
            this.chosenAddressId = defaultMan.id
          }
        }
      })
    },
    onAdd () {
      this.$router.push('/addressAdd')
    },
    // 修改联系人信息
    onEdit (data) {
      this.$router.push({
        path: '/addressUpdate',
        query: {
          id: data.id
        }
      })
    },
    // 选择联系人
    changeContact (data) {
      this.$router.replace({
        path: '/order',
        query: {
          id: data.id
        }
      })
    }
  },
  components: { CommonHead }
}
</script>

<style lang="scss" scoped>

</style>
